import smtplib
import sys
from email.mime.text import MIMEText

import yaml
from flask import Flask, request
import json


app = Flask(__name__)


@app.route("/data", methods=["POST"])
def data_receive():
    return_dict = {"return_code": 201, "return_info": "接收数据成功"}
    if request.get_data() is None:
        return_dict["return_code"] = 404
        return_dict["return_info"] = "未成功接收数据"
        return json.dumps(return_dict, ensure_ascii=False)

    data = request.get_data()
    received_data = json.loads(data)
    print(received_data)
    note_type = received_data.get("type")
    file_content = load_config("email_conf.yaml")

    flag = False
    for k, v in file_content["note_type"][0].items():
        if int(note_type) == int(k):
            print("get in ")
            flag = True
            note = file_content["note_type"][0][int(note_type)]
            tag = received_data.get("tag")
            url = ""
            for i in file_content.get(tag):
                if note in i:
                    url = i
            smtp_host = file_content["smtp_host"]
            smtp_port = file_content["smtp_port"]
            smtp_user = file_content["smtp_user"]
            smtp_pass = file_content["smtp_pass"]
            sender = file_content["email_sender"]
            receivers = file_content["email_send_to"]
            send_email(sender, receivers, smtp_host, smtp_port, smtp_user, smtp_pass, url)
        else:
            continue
    if not flag:
        return_dict["return_code"] = 1001
        return_dict["return_info"] = "非博客、新闻或者活动内容更新"
        return json.dumps(return_dict, ensure_ascii=False)

    return json.dumps(return_dict, ensure_ascii=False)


def load_config(file_path):
    """
       load yaml
       :param file_path: yaml file path
       :return: content of yaml
       """
    with open(file_path, encoding="utf-8") as fp:
        try:
            content = yaml.load(fp.read(), Loader=yaml.Loader)
        except yaml.MarkedYAMLError as e:
            print(e)
            sys.exit(1)
    return content


def get_template(note_info):
    body = """
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Notice</title>
    </head>

    <body leftmargin="8" marginwidth="0" topmargin="8" marginheight="4">
        <table width="95%" cellpadding="0" cellspacing="0"  style="font-size: 11pt; font-family: Tahoma, Arial, Helvetica, sans-serif">
            <tr>
                This email is sent automatically, no need to reply!<br>
                <br>
                website-link<br>
                <br>
                <td><font color="#CC0000">{0}</font></td>
            </tr>
        </table>
    </body>
    </html>
    """.format(note_info)
    return body


def send_email(sender, receivers, smtp_host, smtp_port, smtp_user, smtp_pass, url):

    html_body = get_template(url)
    print('获取模板')
    msg = MIMEText(html_body, 'html', 'utf-8')
    msg['From'] = 'noReply<{}>'.format(sender)
    msg['To'] = receivers
    msg['Subject'] = 'https://gitee.com/mindspore/mindspore.github.io后台数据已刷新'
    try:
        server = smtplib.SMTP(smtp_host, smtp_port)
        server.ehlo()
        server.starttls()
        server.login(smtp_user, smtp_pass)
        print('登录成功')
        server.sendmail(sender, receivers.split(','), msg.as_string())
        print('已发送')
    except TimeoutError:
        print('连接服务超时')
        sys.exit(1)


if __name__ == '__main__':
    app.run(host="192.168.0.186", port="51234")
